package com.net.common.enums.jackson;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.EnumDeserializer;
import com.fasterxml.jackson.databind.util.EnumResolver;
import com.net.common.enums.base.IntEnum;
import com.net.common.enums.base.StringEnum;

/**
 * @author  on 2017/6/8.
 * 处理Enum的jackson反序列化逻辑
 */
public class EnumJacksonDeserializer extends EnumDeserializer {
    EnumJacksonDeserializer(EnumResolver byNameResolver, boolean caseInsensitive) {
        super(byNameResolver, caseInsensitive);
    }

    private Object convert(Class<?> clazz, int val) {
        IntEnum[] objs = (IntEnum[]) clazz.getEnumConstants();
        for (IntEnum em : objs) {
            if (em.getValue() == val) {
                return em;
            }
        }
        return null;
    }

    private Object convert(Class<?> clazz, String val) {
        StringEnum[] objs = (StringEnum[]) clazz.getEnumConstants();
        for (StringEnum em : objs) {
            if (em.getValue().equals(val)) {
                return em;
            }
        }
        return null;
    }

    @Override
    public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        if (IntEnum.class.isAssignableFrom(_valueClass)) {
            JsonToken curr = p.getCurrentToken();
            if (curr == JsonToken.VALUE_NUMBER_INT) {
                return convert(_valueClass, p.getIntValue());
            } else if (curr == JsonToken.VALUE_STRING) {
                String str = p.getValueAsString();
                try {
                    return convert(_valueClass, Integer.valueOf(str));
                } catch (NumberFormatException e) {
                    return null;
                }
            }
        } else if (StringEnum.class.isAssignableFrom(_valueClass)) {
            JsonToken curr = p.getCurrentToken();
            if (curr == JsonToken.VALUE_STRING) {
                return convert(_valueClass, p.getValueAsString());
            }
        } else {
            return super.deserialize(p, ctxt);
        }
        return null;
    }
}
